package com.springapp.mvc.dao;

import com.springapp.mvc.entity.*;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created by dbychkov on 23.12.2014.
 */
public class Mappers {

    public static final BeanPropertyRowMapper<Comment> COMMENT_MAPPER = new BeanPropertyRowMapper<Comment>(Comment.class);


    public static final BeanPropertyRowMapper<Role> ROLE_MAPPER = new BeanPropertyRowMapper<Role>(Role.class);


    public static final BeanPropertyRowMapper<UserPost> USER_POST_MAPPER = new BeanPropertyRowMapper<UserPost>(UserPost.class);


    public static final BeanPropertyRowMapper<Post> POST_MAPPER = new BeanPropertyRowMapper<Post>(Post.class);


    public static final RowMapper<Group> GROUP_MAPPER = new RowMapper<Group>() {
        @Override
        public Group mapRow(ResultSet resultSet, int i) throws SQLException {
            Group g = new Group();
            g.setGroupName(resultSet.getString("name"));
            g.setId(resultSet.getLong("id"));
            return g;
        }
    };

    public static final RowMapper<User> USER_MAPPER = new RowMapper<User>() {
        @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            User mappedUser = new User();
            mappedUser.setId(resultSet.getLong("id"));
            mappedUser.setName(resultSet.getString("name"));
            mappedUser.setPassword(resultSet.getString("password"));
            mappedUser.setGroupId(resultSet.getLong("group_id"));
            return mappedUser;
        }
    };

    public static final RowMapper<CommentForPost> COMMENTS_FOR_POST_MAPPER =
                                    new RowMapper<CommentForPost>() {

        @Override
        public CommentForPost mapRow(ResultSet rs, int i) throws SQLException {
            CommentForPost c = new CommentForPost();
            c.setId(rs.getLong("comment_id"));
            c.setCommentUserId(rs.getLong("comment_user_id"));
            c.setCommentPostId(rs.getLong("post_id"));
            c.setCommentTime(convert(rs.getTimestamp("comment_date_created")));
            c.setCommentText(rs.getString("comment_text"));
            c.setCommentUsername(rs.getString("user_name"));
            return c;
        }

        private Date convert(Timestamp timestamp){
            long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
            return new java.util.Date(milliseconds);
        }


    };
}
